class AutoUploadWebPackPlugin {
  constructor(options) {
    this.ssh = new NodeSSH();
    this.options = options;
  }
  apply(compiler) {
    //完成的事情：注册hooks监听事件
    console.log("AutoUploadWebPackPlugin被注册");
    compiler.hooks.afterEmit.tapAsync("AutoUploadWebPackPlugin", async (compilation, cb) => {
      //1.获取输出文件夹路径（其中资源）
      const outputPath = compilation.outputOptions.path;
      console.log(outputPath, "outputPath");

      //2.连接远程服务器ssh
      await this.connectServer();

      const remotePath = this.options.remotePath;

      //3.删除原有文件夹中的内容
      await this.ssh.execCommand(`rm -rf ${remotePath}`);

      //4.将文件夹中资源上传到服务器中
      await this.uploadFiles(outputPath, remotePath);

      //5.关闭ssh连接
      this.ssh.dispose();

      //6.完成所有的操作后，调用cb
      cb();
    });
  }

  async connectServer() {
    await this.ssh.connect({
      host: this.options.host, //主机名称
      username: this.options.username, //用户名
      password: this.options.password, //密码
    });
  }

  async uploadFiles(localPath, remotePath) {
    const status = await this.ssh.putDirectory(localPath, remotePath, {
      recursive: true,
      concurrency: 10,
    });
    if (status) {
      console.log("文件上传服务器成功");
    }
  }
}

module.exports = AutoUploadWebPackPlugin;
module.exports.AutoUploadWebPackPlugin = AutoUploadWebPackPlugin;
